<script lang="tsx">
import { defineComponent, ref, h } from 'vue';
import { ElMessage } from 'element-plus';
import { Ban, Pencil, SquarePlay } from '@vben/icons';
import { $t } from '@vben/locales';
import { getTenantPageApi, createTenantApi, updateTenantApi, updateTenantStatusApi } from '#/api/system/tenant';
import { usePage } from '#/hooks/page/usePage';
import TenantForm from './modules/tenant/tenant-form.vue';
import StatusComponent from './modules/components/status.vue';
import { ENABLE_VALUE, DISABLE_VALUE, enableDisableOptions as statusOptions } from './const';
import { tenantTypeOptions } from '#/types/const';
import { useCodeBox } from '#/hooks/useCodeBox';
import { verifyPhoneCodeApi } from '#/api/core/auth';


export default defineComponent({
  name: 'Tenant',
  setup() {
    // 表单相关状态
    const showForm = ref(false);
    const formMode = ref('add');
    const { showCodeBox, authCode } = useCodeBox();
    const currentFormData = ref({} as Record<string, any>);    // API配置
    const API = {
      get: getTenantPageApi
    };

    // 表格列配置
    const columns = [
      {
        prop: 'tenantName',
        label: $t('system.organization.tenantName'),
        minWidth: 130,
        showOverflowTooltip: true
      },
      {
        prop: 'userCount',
        label: $t('system.organization.userCount'),
        minWidth: 90
      },
      {
        prop: 'type',
        label: $t('system.organization.tenantType'),
        minWidth: 100,
        formatter: (row: any) => {
          const option = tenantTypeOptions.find(opt => opt.value === row.type);
          return option ? option.label : row.tenantType;
        }
      },
      {
        prop: 'contact',
        label: $t('system.organization.contact'),
        minWidth: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'contactPhone',
        label: $t('system.organization.phone'),
        minWidth: 140,
      },
      {
        prop: 'contactEmail',
        label: $t('system.organization.email'),
        minWidth: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'domain',
        label: $t('system.organization.domain'),
        minWidth: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'status',
        label: $t('system.organization.status'),
        minWidth: 100,
        formatter: (row: any) => {
          return <StatusComponent status={row.status} enableValue={ENABLE_VALUE} disableValue={DISABLE_VALUE} ></StatusComponent>
        }
      },
      {
        prop: 'activeTime',
        label: $t('system.organization.validTime'),
        minWidth: 200,
        showOverflowTooltip: true
      },
      {
        prop: 'createTime',
        label: $t('system.organization.createTime'),
        minWidth: 180,
        showOverflowTooltip: true
      },
    ];

    // 查询配置
    const queryColumns = [
      {
        prop: 'name',
        label: $t('system.organization.tenantName'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('system.organization.tenantName')]),
      },
      {
        prop: 'contact',
        label: $t('system.organization.contact'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('system.organization.contact')]),
      },
      {
        prop: 'contactPhone',
        label: $t('system.organization.phone'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('system.organization.phone')]),
      },
      {
        prop: 'contactEmail',
        label: $t('system.organization.email'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('system.organization.email')]),
      },
      {
        prop: 'domain',
        label: $t('system.organization.domain'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('system.organization.domain')]),
      },
      {
        prop: 'status',
        label: $t('system.organization.status'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('system.organization.status')]),
        options: statusOptions,
      },
    ];

    // 操作按钮配置
    const commands = [
      {
        key: 'status',
        icon: Ban,
        width: 40,
        render: (row: any, index?: number) => {
          const isActive = row.status === ENABLE_VALUE;
          return (
            <el-tooltip
              effect="dark"
              content={isActive ? $t('common.fiddenTxt', ['']) : $t('common.useTxt')}
              show-after={600}
              placement="top"
            >
              <el-button
                link
                icon={isActive ? Ban : SquarePlay}
                onClick={() => tableHandle('status', row, index)}
              />
            </el-tooltip>
          );
        },
      },
      {
        key: 'edit',
        width: 40,
        label: $t('common.editTxt', ['']),
        icon: Pencil,
      },
    ];

    // 自定义操作处理
    const handleCommand = (type: string, data?: any, index?: number) => {
      if (type === 'status') {
        // 切换状态
        if (data.status === ENABLE_VALUE) {
          showCodeBox({
            message: h('div', {}, [
              h('div', {}, [
                $t('system.organization.messages.updatePhoneTipFixed', [data.adminName, data.adminPhone])
              ])
            ]),
            adminName: data.adminName,
            adminPhone: data.adminPhone,
            callback: async (done: any) => {
              const res = await verifyPhoneCodeApi({
                phoneNumber: data.adminPhone,
                verificationCode: authCode.value
              })
              if (res === 'SUCCESS') {
                await updateTenantStatusApi({ id: data.id, status: DISABLE_VALUE })
                ElMessage.success($t('system.organization.messages.disableSuccess'));
                done();
                getTableData();
              }
            }
          })
        } else {
          updateTenantStatusApi({ id: data.id, status: ENABLE_VALUE }).then(() => {
            ElMessage.success($t('system.organization.messages.enableSuccess'));
            getTableData();
          });
        }
      } else if (type === 'edit') {
        // 编辑
        formMode.value = 'edit';
        currentFormData.value = { ...data };
        showForm.value = true;
      }
    };

    const { render, tableHandle, getTableData } = usePage({
      API,
      operateProps: {
        fixed: 'right',
      },
      columns,
      queryColumns,
      commands,
      handleCommand,
    });

    // 新增租户
    const handleAdd = () => {
      formMode.value = 'add';
      currentFormData.value = {};
      showForm.value = true;
    };

    // 表单确认
    const handleFormConfirm = async (formData: any) => {
      try {
        if (currentFormData.value.id) {
          await updateTenantApi(formData);
        } else {
          await createTenantApi(formData);
        }
        showForm.value = false;
        getTableData();
        ElMessage.success($t(currentFormData.value.id ? 'system.organization.messages.updateSuccess' : 'system.organization.messages.createSuccess'));
      } catch (error) {
        console.error($t('tenant.submitFailed'), error);
      }
    };

    // 表单取消
    const handleFormCancel = () => {
      showForm.value = false;
      currentFormData.value = {};
    };

    return () => (
      <div>
        {
          render({
            header: (<el-button type="primary" onClick={handleAdd}>{$t('common.newTxt')}</el-button>)
          })
        }
        <TenantForm
          modelValue={showForm.value}
          onUpdate:modelValue={(val: boolean) => showForm.value = val}
          formData={currentFormData.value}
          mode={formMode.value}
          onConfirm={handleFormConfirm}
          onCancel={handleFormCancel}
        />
      </div>
    );
  }
});
</script>
